<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, DesDev, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
    class upgrade {
        private $tables=array(
			TABLE_PRODUCTS => "products_id",
			TABLE_PRODUCTS_DESCRIPTION => "products_id",
			TABLE_PRODUCTS_ATTRIBUTES => "products_id",
			TABLE_PRODUCTS_OPTIONS => "options_id",
			TABLE_PRODUCTS_OPTIONS_VALUES => "options_values_id",
			TABLE_CONFIGURATION => "configuration_id",
			TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS => "products_options_values_to_products_options_id",
			TABLE_CATEGORIES => "categories_id",
			TABLE_CATEGORIES_DESCRIPTION => "categories_id",
			TABLE_PRODUCTS_TO_CATEGORIES => "categories_id",
			TABLE_CUSTOMERS => "customers_id",
			TABLE_SPECIALS => "specials_id",
			TABLE_SALEMAKER_SALES => "sale_id",
			TABLE_FEATURED => "featured_id",
			TABLE_MANUFACTURERS => "manufacturers_id",
			TABLE_TEMPLATE_SELECT => "template_id",
			TABLE_EZPAGES => "pages_id",
			TABLE_REVIEWS => "reviews_id",
			TABLE_REVIEWS_DESCRIPTION => "reviews_id",
			TABLE_ORDERS_PRODUCTS => "orders_id"
		);
			
		function Run(){
			$this->importBlogfile();
			$this->createBlogTable();
			$this->editTable($this->tables);
			$this->addTable();
			$this->createTrigger($this->tables);
			$this->readyFile();
			$this->fileSpeed();
			$this->showMsg('Success');
			exit;
		}
		//修改表信息
		function editTable($tables){
			global $db;
			foreach($tables as $k => $v){
				$sql="";
				switch($k){
					case TABLE_PRODUCTS:
						$sql="alter table ".$k." add (products_image_detail varchar(800) null,products_vedio varchar(800) null)";
					break;
					case TABLE_PRODUCTS_DESCRIPTION:
					    $sql="alter table ".$k." modify column products_description mediumtext null,modify column products_name varchar(255) not null";
					break;
					case TABLE_TEMPLATE_SELECT:
						$sql="alter table ".$k." add template_device int(5) not null default 0 after template_language"; 
					break;
				}
				if($sql){
					$db->query($sql);
					$this->showMsg('OpenzcTPL ...............表`'.$k."`的字段信息已修改完成 ");
				}
			}
		}
		//新建表
		function addTable(){
			global $db;
			$sql="select table_name from information_schema.tables where table_schema='".DB_DATABASE."'";
			$tables=$db->query($sql);
			$tables=$this->tableList($tables,"table_name");
			
			if(!array_key_exists(DB_PREFIX."products_options_values_image",$tables)){
				$sql="CREATE TABLE `".DB_PREFIX."products_options_values_image` (
					`products_options_values_id` int(11) NOT NULL,
					`products_options_values_color` varchar(100) DEFAULT NULL,
					`products_options_values_image` varchar(255) DEFAULT NULL,
					PRIMARY KEY (`products_options_values_id`)
					)";
				$db->query($sql);
			}
		}
		//创建Openzc触发器
		function createTrigger($tables){
			global $db;
			$sql = "drop table if exists ".TABLE_OPENZC_TRIGGER;
			$db->query($sql);
			$sql = "CREATE TABLE ".TABLE_OPENZC_TRIGGER." (
					id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
					table_name VARCHAR(100) NOT NULL,
					action VARCHAR(100) NOT NULL,
					field VARCHAR(100) NOT NULL,
					value VARCHAR(100) NOT NULL,
					status VARCHAR(5) default 1 NOT NULL,
					last_modified INT(11) NOT NULL
				)";
			$db->query($sql);
			
			$action=array("update","delete","insert");
			foreach($tables as $k => $v){
				foreach($action as $a => $b){
					$trigger_name="trigger_".$b."_".$k;
					$sql = "DROP TRIGGER IF EXISTS ".$trigger_name;
					$db->query($sql);
					$sql = "create trigger ".$trigger_name."
							before ".$b." on ".$k." 
							for each row";
					if($k==TABLE_PRODUCTS_DESCRIPTION && $b=="update"){
						$sql .= " if new.products_viewed = old.products_viewed then
							insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',new.".$v.",unix_timestamp(now()));
							end if";
					}else if($b=="delete"){
						$sql .= " insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',old.".$v.",unix_timestamp(now()))";
					}
					else{
						$sql .= " insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',new.".$v.",unix_timestamp(now()))";
					}
					$db->query($sql);
				}
			}
		}
		//导入博客相关文件
		function importBlogfile(){
			$adminDir=$this->getAdmin();
	
			$BlogadminFile=$this->read_all(INSTALL_DIR."files/blog/admin/");
			$BlogincludesFile=$this->read_all(INSTALL_DIR."files/blog/includes/");
			
			foreach($adminDir as $k => $v){
				
				$adminblog="../".$v."/includes/modules/blog/";
				if(!is_dir($adminblog)){mkdir($adminblog,"0777",true);}
				foreach($BlogadminFile as $a => $b){
					$toFile="../".str_replace(INSTALL_DIR."files/blog/admin",$v,$b['file']);
					
					switch($b['type']){
						case "dir":
							if(EXPECTED_DATABASE_VERSION_MINOR>=5 && strstr($b['file'],"/boxes")){
								if(PHP_VERSION>7){continue 2;}else{continue;}
							}
							if(!is_dir($toFile)){mkdir($toFile);}
						break;
						case "file":
							if(EXPECTED_DATABASE_VERSION_MINOR>=5 && (strstr($b['file'],"header_navigation.php") || strstr($b['file'],"blog_dhtml.php"))){
								if(PHP_VERSION>7){continue 2;}else{continue;}
							}
							
							copy($b['file'],$toFile);
						break;
					}
				}
			}
			foreach($BlogincludesFile as $k => $v){
				$toFile="../".str_replace(INSTALL_DIR."files/blog/","",$v['file']);
				
				switch($v['type']){
					case "dir":
						if(!is_dir($toFile)){mkdir($toFile);}
					break;
					case "file":
						copy($v['file'],$toFile);
					break;
				}
			}
			
		}
		function read_all($dir,$result=array()){ 
		
			if(!is_dir($dir))return false; 
			$handle = opendir($dir); 
			if($handle){ 
				while(($fl = readdir($handle)) !== false){ 
					//$temp = iconv('GBK','utf-8',$dir.DIRECTORY_SEPARATOR.$fl);//转换成utf-8格式 
					$temp=str_replace("\\","/",$dir.$fl);
					$temp=str_replace("//","/",$temp);

					if(is_dir($temp) && $fl!='.' && $fl != '..'){
						$file=array("type"=>"dir","file"=>$temp."/");
						$result[]=$file;
						$result=$this->read_all($temp."/",$result); 
					}else{ 
						if($fl!='.' && $fl != '..'){
							$file=array("type"=>"file","file"=>$temp);
							$result[]=$file; 
						} 
					} 
				} 
			}
			return $result;
		}
		//创建博客数据表
		function createBlogTable(){
			global $db;
			$table=array("blog_archives","blog_archives_description","blog_reviews","blog_reviews_description","blog_categories","blog_archives_to_categories","blog_categories_description","blog_seo");
			$sql="select table_name from information_schema.tables where table_schema='".DB_DATABASE."'";
			$tables=$db->query($sql);
			$tables=$this->tableList($tables,"table_name");
			
			//**判断版本>1.5.5添加后台blog导航
			if(EXPECTED_DATABASE_VERSION_MINOR>=5){
				$sql="select * from ".TABLE_ADMIN_MENUS." where menu_key='blog'";
				$check_blog=$db->query($sql);
				if($check_blog->num_rows==0){
					$sql="INSERT INTO ".TABLE_ADMIN_MENUS." (menu_key,language_key,sort_order) VALUES('blog','BOX_HEADING_BLOG','2')";
					$db->query($sql);
				}
			
				$sql="select * from ".TABLE_ADMIN_PAGES." where menu_key='blog'";
				$check_blog=$db->query($sql);
			
				if($check_blog->num_rows!=3){
					$values=" ('blogArchives','BOX_BLOG_CATEGORIES_ARCHIVES','FILENAME_BLOG','blog','Y','1'),('blogReviews','BOX_BLOG_REVIEWS','FILENAME_BLOG_REVIEWS','blog','Y','2'),('blogSeo','BOX_BLOG_SEO','FILENAME_BLOG_SEO','blog','Y','3')";
					$sql="INSERT INTO ".TABLE_ADMIN_PAGES." (page_key,language_key,main_page,menu_key,display_on_menu,sort_order) VALUES".$values;
				
					$db->query($sql);
				}
			}
			
			foreach($table as $k => $v){
				if(!array_key_exists(DB_PREFIX.$v,$tables)){
				switch($v){
					case "blog_archives":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`archives_id` int(11) NOT NULL AUTO_INCREMENT,
								`master_categories_id` int(11) NOT NULL,
								`archives_image` char(100) DEFAULT NULL,
								`archives_flag` set('p','v','r','f','s','h','c') DEFAULT NULL,
								`archives_click` mediumint(8) NOT NULL,
								`archives_type` set('video','image','text') NOT NULL,
								`related_products_id` varchar(20) DEFAULT NULL,
								`related_categories_id` varchar(20) DEFAULT NULL,
								`archives_date_added` datetime NOT NULL,
								`archives_status` tinyint(1) NOT NULL DEFAULT '1',
								`archives_sort_order` int(11) NOT NULL,
								`archives_last_modified` datetime DEFAULT NULL,
								PRIMARY KEY (`archives_id`))";
					break;
					case "blog_archives_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`archives_id` int(11) NOT NULL,
								`language_id` int(2) NOT NULL,
								`archives_name` char(200) NOT NULL,
								`archives_shorttitle` char(200) DEFAULT NULL,
								`archives_keywords` char(200) DEFAULT NULL,
								`archives_description` text,
								`archives_body` text,
								`archives_tag` varchar(255) DEFAULT NULL,
								PRIMARY KEY (`archives_id`,`language_id`)
								)";
					break;
					case "blog_reviews":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`reviews_id` int(11) NOT NULL AUTO_INCREMENT,
								`archives_id` int(11) NOT NULL,
								`customers_name` varchar(64) NOT NULL,
								`customers_id` int(11) NOT NULL,
								`date_added` datetime NOT NULL,
								`reviews_status` tinyint(1) NOT NULL DEFAULT '1',
								PRIMARY KEY (`reviews_id`)
								)";
					break;
					case "blog_reviews_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`reviews_id` int(11) NOT NULL,
								`language_id` int(11) NOT NULL,
								`reviews_text` text NOT NULL,
								PRIMARY KEY (`reviews_id`,`language_id`)
								)";
					break;
					case "blog_categories":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
							  `categories_id` int(11) NOT NULL AUTO_INCREMENT,
							  `categories_image` char(100) DEFAULT NULL,
							  `parent_id` int(11) NOT NULL,
							  `topid` int(11) NOT NULL,
							  `sort_order` int(3) DEFAULT NULL,
							  `date_added` datetime DEFAULT NULL,
							  `categories_status` tinyint(1) NOT NULL DEFAULT '1',
							  `last_modified` datetime DEFAULT NULL,
							  PRIMARY KEY (`categories_id`)
							  )";
					break;
					case "blog_archives_to_categories":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`categories_id` int(11) NOT NULL,
								`archives_id` int(11) NOT NULL,
								PRIMARY KEY (`categories_id`,`archives_id`)
								)";
					break;
					case "blog_categories_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`categories_id` int(11) NOT NULL,
								`language_id` tinyint(2) NOT NULL,
								`categories_name` varchar(32) NOT NULL,
								`categories_keywords` char(80) DEFAULT NULL,
								`categories_description` text,
								`categories_seotitle` varchar(80) DEFAULT NULL,
								PRIMARY KEY (`categories_id`,`language_id`)
								)";
					break;
					case "blog_seo":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`language_id` int(2) NOT NULL,
								`seo_title` varchar(80) NOT NULL,
								`seo_keywords` varchar(100) DEFAULT NULL,
								`seo_description` varchar(255) DEFAULT NULL,
								PRIMARY KEY (`language_id`)
								)";
					break;
				}
				$db->query($sql);
				}
			}
			$this->showMsg("OpenzcTPL ...............博客数据结构已准备完成 ");
		}
		//修改必要文件
		function readyFile(){
			//zencart首页文件
			$adminDir=$this->getAdmin();
			if(!is_file("../includes/openzctpl/config/zcindex.php")){
				copy("../index.php","../includes/openzctpl/config/zcindex.php");
			}
			$file=array(
				0=>array(INSTALL_DIR."files/init_sessions.php",INIT_INCLUDES."overrides/init_sessions.php"),
				1=>array(INSTALL_DIR."files/init_templates.php",INIT_INCLUDES."overrides/init_templates.php"),
				4=>array(INSTALL_DIR."files/header_php.php","../includes/modules/pages/index/header_php.php"),
				5=>array(INSTALL_DIR."files/index.php","../index.php")
			);
			if(EXPECTED_DATABASE_VERSION_MINOR>5.6){
				$file['4']=array(INSTALL_DIR."files/header_php_157.php","../includes/modules/pages/index/header_php.php");
			}
			foreach($adminDir as $k => $v){
				$file[]=array(INSTALL_DIR."files/template_select.php","../".$v."/template_select.php");
			}
			foreach($file as $k => $v){
				copy($v[0],$v[1]);
			}
			$this->showMsg('OpenzcTPL ...............必要文件已准备就绪！');
		}
		//修改文件提速
		function fileSpeed(){
			$file=array("log"=>"../includes/extra_configures/enable_error_logging.php","conf"=>"../includes/configure.php","index_head"=>"../includes/modules/pages/index/header_php.php");
			chmod($file['conf'], 0666);
			foreach($file as $k => $v){
				$content=file_get_contents($v);
				switch($k){
					case "log":
						$content=str_replace("@ini_set('log_errors', 1);","@ini_set('log_errors', 0);",$content);
					break;
					case "conf":
						$content=str_replace("define('DB_SERVER', 'localhost');","define('DB_SERVER', '127.0.0.1');",$content);
					break;
					case "index_head":
						if(!strstr($content,"openzc_template_engine")){
							$content=str_replace("// set the product","if(!isset(\$openzc_template_engine) || \$openzc_template_engine!=true){\r\n// set the product",$content);
							$content=str_replace("// This should","}\r\n// This should be last",$content);
						}
					break;
				}
				$myfile = fopen($v, "w") or die("Unable to open file!");
				fwrite($myfile, $content);
				fclose($myfile);
			}
			chmod($file['conf'], 0444);
		}
		function getAdmin(){
			
			$path=scandir("../");
			$filter=array("images","cache","data","docs","download","editors","email","extras","images","includes","logs","media","pub","zc_install");
			foreach($path as $k => $v){
				if($v != "." && $v !=".."){
					if(is_dir("../".$v)){
						foreach($filter as $a => $b){
							if($v==$b) unset($path[$k]);
						}
					}else{
						unset($path[$k]);
					}
				}else{
					unset($path[$k]);
				}
			}
			
			foreach($path as $k => $v){
				if(file_exists("../".$v."/banner_manager.php") && !file_exists("../".$v."/openzc.version.php")){
					$rs[]=$v;
				}
			}
	
			return $rs;
		}
		//*重置一些不必要的设置*//
		function initResetConfig(){
			global $db;
			$configuration=array("ACCOUNT_COMPANY"=>"false","ACCOUNT_SUBURB"=>"false","ACCOUNT_STATE"=>"false","DISPLAY_PRIVACY_CONDITIONS"=>"false","SHOW_COUNTS"=>"false","SHOW_COUNTS_ADMIN"=>"false");
			$sql="replace into ".TABLE_CONFIGURATION." (`configuration_key`,`configuration_value`) values";
			end($configuration);
			$end=key($configuration);
			foreach($configuration as $k => $v){
				if($k!=$end){
					$sql.=" ('".$k."','".$v."'),";
				}else{
					$sql.=" ('".$k."','".$v."')";
				}
			}
			
			$db->query($sql);
		}
		
		
		//*SQL数据查询转数组*//
        function tableList($data,$index=""){
			$rows=0;
			$list=array();
			if($index){
				while($row = $data->fetch_assoc()){
					$id=$row[$index];
					foreach($row as $k => $v){$list[$id][$k]=$v;}
				}
			}else{
				while($row = $data->fetch_assoc()) {
					foreach($row as $k => $v){$list[$rows][$k]=$v;}
					$rows++;
				}
			}
			return $list;
		}
		
		function showMsg($msg){
			ob_flush();
			flush(); 
			echo "<script>addMsg('".$msg."');</script>\r\n";
		}
		
		function getSondir($dir){
			 $result = array();
        $handle = opendir($dir);
        if ( $handle )
        {
            while ( ( $file = readdir ( $handle ) ) !== false )
            {
                if ( $file != '.' && $file != '..')
                {
                    $cur_path = $dir . DIRECTORY_SEPARATOR . $file;
                    if ( is_dir ( $cur_path ) )
                    {
                        $result['dir'][$cur_path] = $this->getSondir ( $cur_path );
                    }
                    else
                    {
                        $result['file'][] = $cur_path;
                    }
                }
            }
            closedir($handle);
        }
        return $result;
		}

	    
    }
?>